package com.softjourn.punchcard.merchant.activity;

import java.util.regex.Pattern;

import android.content.Intent;

import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;

import com.actionbarsherlock.view.MenuItem;
import com.softjourn.punchcard.merchant.R;
import com.softjourn.punchcard.merchant.lib.NetworkUtil;
import com.softjourn.punchcard.merchant.lib.PropertiesStorage;
import com.softjourn.punchcard.merchant.lib.SessionManager;

public class MainActivity extends ExitDialogSherlockActivity {

	// Session Manager Class
	SessionManager session;

	PropertiesStorage propertiesStorage;

	boolean isClearSession = true;

	private static final int LOGOUT_ITEM_ID = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		session = new SessionManager(MainActivity.this);
		propertiesStorage = new PropertiesStorage(MainActivity.this);

		setContentView(R.layout.activity_main);

		if (session.isLoggedIn()) {

			if (NetworkUtil.isConnectivityActive(getApplicationContext())) {

				Button btnScan = (Button) findViewById(R.id.btn_scan);

				// in some trigger function e.g. button press within your code
				// you should add:
				btnScan.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						try {

							Intent intent = new Intent(
									"com.google.zxing.client.android.SCAN");
							intent.putExtra("SCAN_MODE", "QR_CODE_MODE");

							// To aviod the complete action using dialog box
							intent.setClassName(MainActivity.this,
									"com.google.zxing.client.android.CaptureActivity");

							startActivityForResult(intent, 0);

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Toast.makeText(getApplicationContext(),
									"ERROR:" + e, Toast.LENGTH_LONG).show();
						}
					}
				});

			} else {

				// Error no internet connection
				showAlertDialog(
						getApplicationContext(),
						getResources().getString(
								R.string.no_internet_connection_title),
						getResources().getString(
								R.string.no_internet_connection_mess), false);

			}
		} else {
			Log.e("Main onCre", "On login");
			Intent login = new Intent(MainActivity.this, LoginActivity.class);

			startActivity(login);
			isClearSession = false;
			finish();
		}
	}

	// In the same activity you will need the following to retrieve the results:
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {

			if (resultCode == RESULT_OK) {
				
				String messageQR = intent.getStringExtra("SCAN_RESULT");
				
				if (messageQR.startsWith(getString(R.string.identifier_client))) {

					propertiesStorage.setActiveClient(messageQR.replaceFirst(
							Pattern.quote(getString(R.string.identifier_client)), ""));

					// Launch Client Screen
					Intent client = new Intent(MainActivity.this,
							ClientActivity.class);

					startActivity(client);
					
				} else if (messageQR.startsWith(getString(R.string.identifier_offer))) {
					
					messageQR = messageQR.replaceFirst(
							Pattern.quote(getString(R.string.identifier_offer)), "");
					
					String[] uids = messageQR.split(Pattern.quote(getString(R.string.uid_delimeter)));
					
					propertiesStorage.setActiveOffer(uids[0]);
					
					propertiesStorage.setActivePunchCard(uids[1]);
					
					// Launch Offer Screen
					Intent offer = new Intent(MainActivity.this,
							OfferActivity.class);
					
					startActivity(offer);
					
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "ERROR:",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, LOGOUT_ITEM_ID, LOGOUT_ITEM_ID, R.string.logout)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_ALWAYS
								| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case LOGOUT_ITEM_ID:

			logOut();
			return true;
		}

		return false;
	}

	private void logOut() {

		Log.e("Main onCre", "On login");

		if (isClearSession) {
			session.clearSessionData();

			Intent login = new Intent(MainActivity.this, LoginActivity.class);
			// login.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY );
			startActivity(login);
			finish();
		}
	}

}
